package com.zx._09_架构.rpc演变过程.rpc_01;

import com.zx._09_架构.rpc演变过程.service.impl.UserServiceImpl;
import com.zx.common.entity.UserRpcDto;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import lombok.extern.slf4j.Slf4j;

// 教程视频
// https://www.bilibili.com/video/BV1Ug4y1875i?t=1903&p=2
@Slf4j
public class Server {

    public static void main(final String[] args) throws Exception {
        final ServerSocket ss = new ServerSocket(8888);
        Socket socket = null;
        while ((socket = ss.accept()) != null) {
            process(socket);
            socket.close();
        }
        ss.close();
    }

    public static void process(final Socket socket) throws Exception {
        final InputStream inputStream = socket.getInputStream();
        final OutputStream outputStream = socket.getOutputStream();

        final DataInputStream input = new DataInputStream(inputStream);
        final DataOutputStream output = new DataOutputStream(outputStream);

        // 请求的id
        final long id = input.readLong();
        final UserServiceImpl impl = new UserServiceImpl();
        final UserRpcDto userRpcDto = impl.getById(id);
        log.info("provider = {}", userRpcDto.toString());
        // 将结果写回去
        output.writeLong(userRpcDto.getId());
        output.writeUTF(userRpcDto.getName());

        output.flush();
    }
}
